<template>
  <el-dialog
    v-model="visible"
    title="修改密码"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :append-to-body="true">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="账号">
        <span>{{ store.state.user.name }}</span>
      </el-form-item>
      <el-form-item prop="password" label="原密码">
        <el-input v-model="dataForm.password" type="password" placeholder="原密码"></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" label="新密码">
        <el-input v-model="dataForm.newPassword" type="password" placeholder="新密码"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" label="确认密码">
        <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import debounce from 'lodash/debounce'
import {ref, reactive, computed, nextTick} from "vue";
import http from "../utils/request.js";
import {message} from "../utils/commonScript.js";
import {clearLoginInfo} from "../utils/util.js";
import {useRouter} from "vue-router";
import {useStore} from "vuex";

const store = useStore()
const router = useRouter()
let visible = ref(false)

const dataFormRef = ref()
const dataForm = reactive({
  password: '',
  newPassword: '',
  confirmPassword: ''
})
const dataRule = computed(() => {
  var validateConfirmPassword = (rule, value, callback) => {
    if (this.dataForm.newPassword !== value) {
      return callback(new Error('确认密码与新密码输入不一致'))
    }
    callback()
  }
  return {
    password: [
      { required: true, message: '必填项不能为空', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '必填项不能为空', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '必填项不能为空', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' }
    ]
  }
})

const init = () => {
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
}
// 表单提交
const dataFormSubmitHandle =  debounce(function () {
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      return false
    }
    http.put('/sys/user/password', this.dataForm).then(({ data: res }) => {
      if (res.code !== 0) {
        return message.error(res.msg)
      }
      message({
        message: '操作成功',
        type: 'success',
        duration: 500,
        onClose: () => {
          this.visible = false
          clearLoginInfo()
          router.replace({ name: 'login' })
        }
      })
    }).catch(() => {})
  })
}, 1000, { 'leading': true, 'trailing': false })


defineExpose({
  init
})
</script>
